import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {GroupService} from '../../group/group.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {ActivatedRoute, Router, NavigationEnd} from '@angular/router';
import {adSystemApiUrl, AliyunOssOutputUrl, appletApiUrl} from '../../../../config/api';
import * as moment from 'moment';
import {LocalStorageService} from '../../../lib/service/local-storage.service';
import {ShopService} from '../shop.service';
import {MyShopService} from '../../myshop.service';
import {Subscription} from '../../../../../node_modules/rxjs/Subscription';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss'],
  providers: [ShopService, GroupService, MyShopService, LocalStorageService]
})
export class ListComponent implements OnInit {


  isCollapsed = false;
  typeOpen = true;
  sliderWidth = 180;
  total = 0;
  loading = true;
  pageSize = 10;
  page = 1;
  name = '';
  status = '';
  order = {
    'created_at': 'desc'
  };
  orderJson = {
    'created_at': null
  };
  template_id = '';
  stage = 1;  // 1-	未开始  2-进行中  3-已结束 4-已暂停
  group_type = 0;  // 1 - 普通 2 - 拉新 3 - 抽奖
  groupsList = [];
  checkedIds = [];
  _allChecked = false;
  _indeterminate = false;
  isVisibleMiddle = false;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  qrcodeForm: FormGroup;
  start_date = null;
  end_date = null;
  _checked = false;
  qodeFormStatus = false;
  isLoadingAdd = false;
  qrcodeList = [];
  activityId = null;
  activity_goods_id = null;

  qrcodePageSize = 3;
  qrcodePage = 1;
  qrcodeTotal = 0;
  qrcodePageList = [];
  startIndex = 0;
  endIndex = 0;
  codeLoading = false;
  list = [
    // {'id': 0 , 'name': '店铺宣传图' },
    {'id': 0, 'name': '首页轮播'}
  ];
  showcaseDetailList = [];
  showcaseId = 0;
  templateName;
  boothNumber;
  templateId;
  options = [];
  selectedOption;
  flag = true;
  shopid = 0;
  goto_type = null;


  subscription: Subscription;


  search() {
    this.getCaseDetailList();
  }

  keyDown(e) {
    if (e.code === 'Enter') {
      this.search();
    }
  }

  reset() {
    this.name = name;
    this.page = 1;
    this.getCaseDetailList();
  }

  getCaseDetailList() {
    this._allChecked = false;
    this.checkedIds = [];
    this.loading = true;
    this.getShopList();
  }

  goAddPage() {
    if (this.flag) {
      this.router.navigate([`member/shop/add/${this.shopid}`]
      );
      this.flag = false;
    }
  }

  editPage(item) {
    localStorage.setItem('shop_item', JSON.stringify(item));
    if (this.flag) {
      this.router.navigate([`member/shop/edit`],
        {
          queryParams: {
            id: item.id
          }
        }
      );
      this.flag = false;
    }
  }

  addQodeForm() {
    if (this.qodeFormStatus) {
      return;
    }
    this.qodeFormStatus = true;
  }

  cancelAddCode() {
    if (this.isLoadingAdd) {
      this._message.create('warning', '正在添加中,请勿取消');
      return;
    }
    this.qodeFormStatus = false;
  }

  openType(item, type) { // 打开拼团详情
    item[type] = !item[type];
    const activityId = item.id;
    const activityGoodsId = item.activity_goods[0].id;
    if (item[type] && type == 'showProduct') {
      let flag = true;
      let index = 0;
      this.groupsList.forEach((e, i) => {
        if (e.id == item.id) {
          index = i;
          if (e.goodsInfo) {
            flag = false;
          }
        }
      });
      if (flag) {
        this.groupService.getGoodsDetail(activityId, activityGoodsId).subscribe(res => {
          if (res.data.goods_num) {
            res.data.goods_numList = res.data.goods_num.split('|');
          }
          if (res.data.prize_info) {
            res.data.prize_info.forEach(item3 => {
              if (item3.prize_num) {
                item3.prize_num = item3.prize_num.split('|');
              }
            });
            this.groupsList[index].goodsInfo = res.data;
          } else {
            this.groupsList[index].goodsInfo = res.data;
            this.groupsList[index].goodsInfo.prize_info = [];
          }
        });
      }
    }
    ;
    if (item[type] && type == 'showGroup') {
      let flag = true;
      let index = 0;
      this.groupsList.forEach((e, i) => {
        if (e.id === item.id) {
          index = i;
          if (e.groupInfo) {
            flag = false;
          }
        }
      });
      if (flag) {
        this.groupService.getGroupDetail(activityId, activityGoodsId).subscribe(res => {
          this.groupsList[index].groupInfo = res.data;
        });
      }
    }
  }

  _checkAll(value) {
    if (value) {
      this.showcaseDetailList.forEach(item => {
        if (!item.checked) {
          item.checked = true;
          this.checkedIds.push(item.id);
        }
      });
    } else {
      this.showcaseDetailList.forEach(item => {
        if (item.checked) {
          item.checked = false;
          this.checkedIds.every((val, idx, array) => {
            if (item.id === val) {
              this.checkedIds.splice(idx, 1);
              return false;
            }
            return true;
          });
        }
      });
    }
    this._refreshStatus();
  };

  checkedSingele(e, id) {
    if (e) {
      this.checkedIds.push(id);
    } else {
      this.checkedIds.every((val, idx, array) => {
        if (id === val) {
          this.checkedIds.splice(idx, 1);
          return false;
        }
        return true;
      });
      this.showcaseDetailList.every((val, idx, array) => {
        if (id === val.id) {
          val.checked = false;
          return false;
        }
        return true;
      });

    }
    this._refreshStatus();
  }

  _refreshStatus() {
    const allChecked = this.showcaseDetailList.every(value => value.checked === true);
    const allUnChecked = this.showcaseDetailList.every(value => !value.checked);
    this._allChecked = allChecked;
    this._indeterminate = (!allChecked) && (!allUnChecked);
  };


  toggleCollapsed(value) {
    this.isCollapsed = value;
    if (!this.isCollapsed) {
      this.typeOpen = true;
    }
  }

  constructor(private groupService: GroupService,
              private _message: NzMessageService,
              private confirmServ: NzModalService,
              private activatedRoute: ActivatedRoute,
              private router: Router,
              private fb: FormBuilder,
              private localStorageService: LocalStorageService,
              private shopService: ShopService,
  ) {
    this.router.events
      .filter((event) => event instanceof NavigationEnd)
      .subscribe((event: NavigationEnd) => {
        this.shopid = this.localStorageService.getShop()['id'];

      });

  }

  getFormControl(name) {
    return this.qrcodeForm.controls[name];
  }

  ngOnInit() {
    this.getShopList();
    const self = this;
  }


  detailDel(e, item) {
    e.stopPropagation();
    const self = this;
    this.confirmServ.confirm({
      title: '温馨提示',
      content: '<b>您确定要删除这个店铺吗</b>',
      onOk: () => {
        this.shopService.delShowCaseDetail(item.id).subscribe(res => {
          if (res.code == 200) {
            const _lastCheckedIds = self.checkedIds;
            self._message.create('success', `店铺删除成功`);
            self.page = 1;
            self.getCaseDetailList();
            setTimeout(() => {
              self.checkedIds = [];
              _lastCheckedIds.forEach((e, i) => {
                self.checkedSingele(true, e);
                self.showcaseDetailList.forEach((e1, i1) => {
                  if (e1.id === e) {
                    e1.checked = true;
                  }
                });
              });
              self.checkedSingele(false, item.id);
              if (self.showcaseDetailList.length === 0) {
                self._indeterminate = false;
                self._allChecked = false;
              }
            }, 300);
          } else {
            self._message.create('error', res.message);
          }
        });
      },
      onCancel() {
      }
    });
  }


  getShopList() {
    this.shopService.getShopList().subscribe(res => {
      if (res.code === 200) {
        this.loading = false;
        this.showcaseDetailList = res.data;
        console.log('sd', this.showcaseDetailList);
        this.showcaseId = this.showcaseId ? this.showcaseId : this.list[0]['id'];
        this.list.map((e, i) => {
          if (e.id === this.showcaseId) {
            this.templateName = e['name'];
          }
          ;
        });
        this.showcaseDetailList.map((e, i) => {
          if (e['pic_url']) {
            e['pic_url_s'] = appletApiUrl + '/common/attachment/view?id=' + e['pic_url'];
          }
          ;
        });
      }
    });
  }

  sort(type, value) {
    if (value) {
      this.order[type] = value.substring(0, value.length - 3);
      this.orderJson[type] = value;
    } else {
      this.orderJson[type] = 'descend';
      this.order[type] = 'desc';
    }
    this.page = 1;
    this.getCaseDetailList();
  }

  changeGroupStage(stage) {
    this.stage = stage;
    this.name = '';
    this._allChecked = false;
    this.checkedIds = [];
    this.order = {
      'created_at': 'desc'
    };
    this.orderJson = {
      'created_at': 'descend'
    };

    this.getCaseDetailList();
  }

  deleteCheckedGroup() {
    const self = this;
    if (this.checkedIds.length > 0) {
      this.confirmServ.confirm({
        title: `批量删除展位`,
        content: '您确定要批量删除展位吗？',
        onOk() {
          let num = 0;
          self.checkedIds.map((e, i) => {
            self.shopService.delShowCaseDetail(e).subscribe(res => {
              if (res.code === 200) {
                num++;
                if (num === self.checkedIds.length) {
                  self._message.create('success', `展位批量删除成功`);
                  self.page = 1;
                  self.getCaseDetailList();
                }
              } else {
                self._message.create('error', res.message);
              }
            });
          });
        },
        onCancel() {
        }
      });
    }
  }

  handleCancelMiddle(e) {
    this.isVisibleMiddle = false;
  }

  handleOkMiddle(e) {
    this.isVisibleMiddle = false;
  }

  newArray = (len) => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  }
  _startValueChange = () => {
    if (this.start_date > this.end_date) {
      this.end_date = null;
    }
  }
  _endValueChange = () => {
    if (this.start_date > this.end_date) {
      this.start_date = null;
    }
  }
  _disabledStartDate = (startValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!startValue || !this.qrcodeForm.value.validity_end) {
      return startValue < now_time;
    }
    return (startValue.getTime() >= this.qrcodeForm.value.validity_end.getTime()) || (startValue.getTime() <= Date.now());
  }
  _disabledEndDate = (endValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!endValue || !this.start_date) {
      return endValue.getTime() < now_time;
    }
    return endValue.getTime() < this.start_date.getTime();
  }

  get _isSameDay() {
    return this.start_date && this.end_date && moment(this.start_date).isSame(this.end_date, 'day');
  }

  get _endTime() {
    return {
      nzHideDisabledOptions: true,
      nzDisabledHours: () => {
        return this._isSameDay ? this.newArray(this.start_date.getHours()) : [];
      },
      nzDisabledMinutes: (h) => {
        if (this._isSameDay && h === this.start_date.getHours()) {
          return this.newArray(this.start_date.getMinutes());
        }
        return [];
      },
      nzDisabledSeconds: (h, m) => {
        if (this._isSameDay && h === this.start_date.getHours() && m === this.start_date.getMinutes()) {
          return this.newArray(this.start_date.getSeconds());
        }
        return [];
      }
    };
  }

  getQrCodeList(e?) {
    this.codeLoading = true;
    if (e) {
      this.qrcodePage = e;
    }

    this.startIndex = (this.qrcodePage - 1) * this.qrcodePageSize - (this.qrcodePage != 1 ? 1 : 0);
    this.endIndex = this.qrcodePage * this.qrcodePageSize - (this.qrcodePage != 1 ? 1 : 0);
    // this.startIndex = (this.qrcodePage - 1) * this.qrcodePageSize;
    // this.endIndex = this.qrcodePage * this.qrcodePageSize - 1;
    //分页切换
    // if(this.qrcodePage == 1) {
    //   this.qrcodePageSize = 2;goAddPage()
    // } else {
    //   this.qrcodePageSize = 3;
    // }
    // this.startIndex = (this.qrcodePage - 1) * this.qrcodePageSize + (this.qrcodePage === 1 ? 0 : -1);
    // this.endIndex = this.qrcodePage === 1 ? this.startIndex + 1 : this.startIndex + 2;

    this.groupService.getQrcodeList(this.activityId).subscribe(res => {
      this.codeLoading = false;
      this.qrcodeList = res.data.data;
      if (res.data.total != 0 && res.data.total % 3 == 0) {
        this.qrcodeTotal = res.data.total + 1;
      } else {
        this.qrcodeTotal = res.data.total;
      }
      this.qrcodePageList = [];

      this.qrcodeList.forEach((e, i) => {

        const nowTime = new Date().getTime();
        if (i >= this.startIndex && i <= this.endIndex) {
          if (nowTime > new Date(e['end_date']).getTime() + 86400000) {
            e['invalid'] = true;
          } else {
            e['invalid'] = false;
          }
          this.qrcodePageList.push(e);
        }
      });
    });
  }

  _submitForm() {

  }
}
